/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.com.pps.web.bean.course;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ReverseComparator;
import org.primefaces.event.SelectEvent;
import vn.com.pps.common.util.DateUtils;
import vn.com.pps.entities.Course;
import vn.com.pps.entities.CoursePupil;
import vn.com.pps.entities.CoursePupilDetail;
import vn.com.pps.entities.CourseTeacherAttendance;
import vn.com.pps.entities.CourseTeacherDetail;
import vn.com.pps.entities.CreditMemo;
import vn.com.pps.web.common.component.table.LazyCacheModel;
import vn.com.pps.web.ui.CourseTableItem;

/**
 *
 * @author Dai
 */
public class CourseManageBean extends LazyCacheModel implements Serializable {

    private int rowCount = 0;
    private int selectedID = 0;
    private Course course;
    private int startedMonth = 0;
    private int indexMonth1 = 0;
    private int indexMonth2 = 0;
    private int indexMonth3 = 0;
    private int indexMonth4 = 0;
    private int indexMonth5 = 0;
    private int indexMonth6 = 0;
    private String selectedTabIdx;
    private int selectedCoursePupilID;
    private int selectedTeacherAttendentID;
    private int selectedCreditMemoID;
    private String criterial = "1=1";
    private int selectedNewCourseID;
    private String criterialCourseName;
    private int criterialCourseType;
    private int criterialCourseLevel;
    private String criterialStartedDate;
    private String criterialStatus;
    private int criterialCourseID;

    private CourseTeacherDetail courseTeacher;
    private ArrayList<CourseTableItem> courses = new ArrayList<CourseTableItem>();

    @Override
    protected void init() {
        rowCount = getServiceLocator().getCourseService().countCourse(criterial);
        courses = getServiceLocator().getCourseService().getCourses(getTargetPage(), getMaximumPageSize(), criterial);
        setPageItems(courses);
        setRowCount(rowCount);
    }

    @Override
    public void sort(String pm_column, boolean pm_ascending) {
        Comparator<CourseTableItem> bc = null;
        if (pm_ascending) {
            bc = new BeanComparator(pm_column);
        } else {
            bc = new BeanComparator(pm_column, new ReverseComparator(new ComparableComparator()));
        }
        Collections.sort(getPageItems(), bc);
    }

    @Override
    public void loadData() {
        System.out.println("Criterial:::"+criterial);
        rowCount = getServiceLocator().getCourseService().countCourse(criterial);
        courses = getServiceLocator().getCourseService().getCourses(getTargetPage(), getMaximumPageSize(), criterial);
        setPageItems(courses);
        setRowCount(rowCount);
    }

    public void search() {
        criterial = " 1=1";
        if(criterialCourseID != 0){
            criterial += " AND tblcourses.ID=" + criterialCourseID;
        }
        if (criterialCourseName.trim().length() > 0) {
            criterial += " AND tblcourses.CourseName LIKE %'" + criterialCourseName + "'%";
        }
        if (criterialCourseType != 0) {
            criterial += " AND tblcourses.CourseType=" + criterialCourseType;
        }

        if (criterialCourseLevel != 0) {
            criterial += " AND tblcourses.CourseLevelID=" + criterialCourseLevel;
        }

        if (criterialStartedDate.trim().length() > 0) {
            SimpleDateFormat formDate = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date startDate = DateUtils.stringToDate(criterialStartedDate);
                criterial += " AND tblcourses.StartedDate >='" + formDate.format(startDate) + "'";
            } catch (ParseException ex) {
                ex.printStackTrace();
            }

        }
        
        if (criterialStatus.trim().length()>0){
            criterial += " AND tblcourses.Status='" + criterialStatus+"'";
        }

        System.out.println("criterialStartedDate:" + criterialStartedDate);
        System.out.println("criterialCourseType:" + criterialCourseType);
        System.out.println("criterialCourseLevel:" + criterialCourseLevel);
        System.out.println("criterialStatus:" + criterialStatus);
        System.out.println("Where:::"+criterial);
        loadData();
    }
    
    
    public void reset() {
        criterialCourseName = "";
        criterialCourseType = 0;
        criterialCourseLevel = 0;
        criterialStartedDate = null;
        criterialStatus = "";
    }

    public int getSelectedID() {
        return selectedID;
    }

    public void setSelectedID(int selectedID) {
        this.selectedID = selectedID;
    }

    public Course getCourse() {
        return course;
    }

    public String viewCourse() {
        course = getServiceLocator().getCourseService().getCourse(selectedID);
        Calendar cal = Calendar.getInstance();
        cal.setTime(course.getStartedDate());
        startedMonth = cal.get(Calendar.MONTH);
        indexMonth1 = getMonthInx(startedMonth, 0);
        indexMonth2 = getMonthInx(startedMonth, 1);
        indexMonth3 = getMonthInx(startedMonth, 2);
        indexMonth4 = getMonthInx(startedMonth, 3);
        indexMonth5 = getMonthInx(startedMonth, 4);
        indexMonth6 = getMonthInx(startedMonth, 5);
        System.out.println("1");
        courseTeacher = getServiceLocator().getCourseService().getTeacherByCourse(selectedID);
       
        System.out.println("ID:"+selectedID); 
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CoursePupilBean coursePupilBean
                = (CoursePupilBean) facesContext.getApplication()
                .createValueBinding("#{coursePupilBean}").getValue(facesContext);
        coursePupilBean.setCourseID(selectedID);
        coursePupilBean.setTargetPage(1);
        coursePupilBean.loadData();
        System.out.println("2");
        LessonRecordBean lessonRecordBean
                = (LessonRecordBean) facesContext.getApplication()
                .createValueBinding("#{lessonRecordBean}").getValue(facesContext);
        lessonRecordBean.setCourseID(selectedID);
        lessonRecordBean.setTargetPage(1);
        lessonRecordBean.loadData();
        System.out.println("3");
        CreditMemoBean creditMemoBean
                = (CreditMemoBean) facesContext.getApplication()
                .createValueBinding("#{creditMemoBean}").getValue(facesContext);
        creditMemoBean.setCourseID(selectedID);
        creditMemoBean.setTargetPage(1);
        creditMemoBean.loadData();
        System.out.println("4");
        return "success";
    }

    public String preAddCredit() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CreditMemo creditMemoEntity
                = (CreditMemo) facesContext.getApplication()
                .createValueBinding("#{creditMemoEntity}").getValue(facesContext);
        creditMemoEntity.setCourseID(selectedID);

        return "success";
    }

    public String addCredit() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CreditMemo creditMemoEntity
                = (CreditMemo) facesContext.getApplication()
                .createValueBinding("#{creditMemoEntity}").getValue(facesContext);
        getServiceLocator().getCourseService().saveCreditMemo(creditMemoEntity);
        CreditMemoBean creditMemoBean
                = (CreditMemoBean) facesContext.getApplication()
                .createValueBinding("#{creditMemoBean}").getValue(facesContext);
        creditMemoBean.setCourseID(selectedID);
        creditMemoBean.setTargetPage(1);
        creditMemoBean.loadData();
        return "success";
    }

    public String preCourseTeacherAttend() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CourseTeacherAttendance courseTeacherAttendance
                = (CourseTeacherAttendance) facesContext.getApplication()
                .createValueBinding("#{courseTeacherAttendance}").getValue(facesContext);
        courseTeacherAttendance.setCourseID(selectedID);
        courseTeacherAttendance.setCourseName(courseTeacher.getCourseName());
        courseTeacherAttendance.setTeacherID(courseTeacher.getTeacherID());
        courseTeacherAttendance.setTeacherName(courseTeacher.getFullName());
        return "success";
    }

    public String preUpdateCourseTeacherAttend() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CourseTeacherAttendance courseTeacherAttendance
                = (CourseTeacherAttendance) facesContext.getApplication()
                .createValueBinding("#{courseTeacherAttendance}").getValue(facesContext);
        CourseTeacherAttendance tmp = getServiceLocator().getCourseService().getTeacherAttendanceByID(selectedTeacherAttendentID);
        courseTeacherAttendance.setId(tmp.getId());
        courseTeacherAttendance.setCourseID(tmp.getCourseID());
        courseTeacherAttendance.setTeacherID(tmp.getTeacherID());
        courseTeacherAttendance.setAttendedYN(tmp.getAttendedYN());
        courseTeacherAttendance.setDateTo(tmp.getDateTo());
        courseTeacherAttendance.setLastModifiedDate(tmp.getLastModifiedDate());
        courseTeacherAttendance.setCreatedDate(tmp.getCreatedDate());
        courseTeacherAttendance.setNote(tmp.getNote());
        courseTeacherAttendance.setTeacherName(tmp.getTeacherName());
        courseTeacherAttendance.setMobile(tmp.getMobile());
        courseTeacherAttendance.setCourseName(tmp.getCourseName());
        return "success";
    }

    public String updateCourseTeacherAttend() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CourseTeacherAttendance courseTeacherAttendance
                = (CourseTeacherAttendance) facesContext.getApplication()
                .createValueBinding("#{courseTeacherAttendance}").getValue(facesContext);
        Calendar calendar = Calendar.getInstance();
        java.sql.Timestamp currentTimeStamp = new java.sql.Timestamp(calendar.getTime().getTime());
        courseTeacherAttendance.setCreatedDate(currentTimeStamp);
        courseTeacherAttendance.setLastModifiedDate(currentTimeStamp);
        getServiceLocator().getCourseService().editTeacherAttendance(courseTeacherAttendance);
        LessonRecordBean lessonRecordBean
                = (LessonRecordBean) facesContext.getApplication()
                .createValueBinding("#{lessonRecordBean}").getValue(facesContext);
        lessonRecordBean.setCourseID(selectedID);
        lessonRecordBean.setTargetPage(1);
        lessonRecordBean.loadData();
        return "success";
    }

    public void deleteCourseTeacherAttend() {
        System.out.println("@deleteCourseTeacherAttend::" + selectedTeacherAttendentID);
        getServiceLocator().getCourseService().deleteteacherAttendance(selectedTeacherAttendentID);
        FacesContext facesContext = FacesContext.getCurrentInstance();
        LessonRecordBean lessonRecordBean
                = (LessonRecordBean) facesContext.getApplication()
                .createValueBinding("#{lessonRecordBean}").getValue(facesContext);
        lessonRecordBean.setCourseID(selectedID);
        lessonRecordBean.setTargetPage(1);
        lessonRecordBean.loadData();

    }

    public String addCourseTeacherAttendance() {
        System.out.println("@addCourseTeacherAttendance");
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CourseTeacherAttendance courseTeacherAttendance
                = (CourseTeacherAttendance) facesContext.getApplication()
                .createValueBinding("#{courseTeacherAttendance}").getValue(facesContext);
        courseTeacherAttendance.setAttendedYN("Y");
        Calendar calendar = Calendar.getInstance();
        java.sql.Timestamp currentTimeStamp = new java.sql.Timestamp(calendar.getTime().getTime());
        courseTeacherAttendance.setCreatedDate(currentTimeStamp);
        courseTeacherAttendance.setLastModifiedDate(currentTimeStamp);
        getServiceLocator().getCourseService().saveTeacherAttendance(courseTeacherAttendance);

        LessonRecordBean lessonRecordBean
                = (LessonRecordBean) facesContext.getApplication()
                .createValueBinding("#{lessonRecordBean}").getValue(facesContext);
        lessonRecordBean.setCourseID(selectedID);
        lessonRecordBean.setTargetPage(1);
        lessonRecordBean.loadData();

        return "success";
    }

    public String preUpdateCreditMemo() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CreditMemo creditMemoEntity
                = (CreditMemo) facesContext.getApplication()
                .createValueBinding("#{creditMemoEntity}").getValue(facesContext);
        CreditMemo tmp = getServiceLocator().getCourseService().getCreditMemo(selectedCreditMemoID);
        creditMemoEntity.setAmount(tmp.getAmount());
        creditMemoEntity.setCourseID(tmp.getCourseID());
        creditMemoEntity.setCreatedBy("daimx");
        creditMemoEntity.setReason(tmp.getReason());
        creditMemoEntity.setLastModifiedDate(tmp.getLastModifiedDate());
        creditMemoEntity.setCreatedDate(tmp.getCreatedDate());
        creditMemoEntity.setCreditType(tmp.getCreditType());
        creditMemoEntity.setId(tmp.getId());
        return "success";
    }

    public String updateCreditMemo() {
        System.out.println("@updateCreditMemo");
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CreditMemo creditMemoEntity
                = (CreditMemo) facesContext.getApplication()
                .createValueBinding("#{creditMemoEntity}").getValue(facesContext);
        Calendar calendar = Calendar.getInstance();
        java.sql.Timestamp currentTimeStamp = new java.sql.Timestamp(calendar.getTime().getTime());
        creditMemoEntity.setLastModifiedDate(currentTimeStamp);
        getServiceLocator().getCourseService().editCourseCreditMemo(creditMemoEntity);
        System.out.println("@Finish updateCreditMemo");

        CreditMemoBean creditMemoBean
                = (CreditMemoBean) facesContext.getApplication()
                .createValueBinding("#{creditMemoBean}").getValue(facesContext);
        creditMemoBean.setCourseID(selectedID);
        creditMemoBean.setTargetPage(1);
        creditMemoBean.loadData();
        return "success";
    }

    public void deleteCreditMemo() {
        getServiceLocator().getCourseService().deleteCourseCreditMemo(selectedCreditMemoID);
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CreditMemoBean creditMemoBean
                = (CreditMemoBean) facesContext.getApplication()
                .createValueBinding("#{creditMemoBean}").getValue(facesContext);
        creditMemoBean.setCourseID(selectedID);
        creditMemoBean.setTargetPage(1);
        creditMemoBean.loadData();
    }

    public String changeCourse() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        CoursePupilDetail coursePupilDetail
                = (CoursePupilDetail) facesContext.getApplication()
                .createValueBinding("#{coursePupilDetail}").getValue(facesContext);
        System.out.println("Current CourseID:" + coursePupilDetail.getCourseID());
        System.out.println("Change to courseID:" + selectedNewCourseID);
        System.out.println("PupilID:" + coursePupilDetail.getPupilID());

        CoursePupil coursePuipl = new CoursePupil();
        coursePuipl.setCourseID(coursePupilDetail.getCourseID());
        coursePuipl.setPupilID(coursePupilDetail.getPupilID());
        coursePuipl.setId(coursePupilDetail.getId());

        getServiceLocator().getCourseService().editChangeCourse(coursePuipl, selectedNewCourseID);

        CoursePupilBean coursePupilBean
                = (CoursePupilBean) facesContext.getApplication()
                .createValueBinding("#{coursePupilBean}").getValue(facesContext);
        coursePupilBean.setCourseID(selectedID);
        coursePupilBean.setTargetPage(1);
        coursePupilBean.loadData();
        return "success";
    }
    
    public String createCourse(){
        System.out.println("@createCourse");
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Course course
                = (Course) facesContext.getApplication()
                .createValueBinding("#{courseEntity}").getValue(facesContext);
        int courseID = getServiceLocator().getCourseService().saveCourse(course);
        loadData();
        return "success";
    }
    
    
    public String preAddCourse(){
       
       // courseEntity.set
        return  "success";
    }
    
    public String preUpdateCourse()
    {
        
        course = getServiceLocator().getCourseService().getCourse(selectedID);
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Course courseEntity
                = (Course) facesContext.getApplication()
                .createValueBinding("#{courseEntity}").getValue(facesContext);
        courseEntity.setCourseName(course.getCourseName());
        courseEntity.setCourseLevelID(course.getCourseLevelID());
        courseEntity.setCourseType(course.getCourseType());
        courseEntity.setScheduler(course.getScheduler());
        courseEntity.setTimeFrame(course.getTimeFrame());
        courseEntity.setDescription(course.getDescription());
        courseEntity.setStatus(course.getStatus());
        courseEntity.setStartedDate(course.getStartedDate());
        courseEntity.setCreatedDate(course.getCreatedDate());
        courseEntity.setLastModifiedDate(course.getLastModifiedDate());
        courseEntity.setId(course.getId());   
        return "success";
    }

    
    public String updateCourse()
    {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Course courseEntity
                = (Course) facesContext.getApplication()
                .createValueBinding("#{courseEntity}").getValue(facesContext);
        java.util.Date date = new java.util.Date();
        courseEntity.setLastModifiedDate(new Timestamp(date.getTime()));
        getServiceLocator().getCourseService().editCourse(courseEntity);
        System.out.println("Done:updateCourse");
        return "success";
    }
    

    public int getStartedMonth() {
        return startedMonth;
    }

    public int getIndexMonth1() {
        return indexMonth1;
    }

    public int getIndexMonth2() {
        return indexMonth2;
    }

    public int getIndexMonth3() {
        return indexMonth3;
    }

    public int getIndexMonth4() {
        return indexMonth4;
    }

    public int getIndexMonth5() {
        return indexMonth5;
    }

    public int getIndexMonth6() {
        return indexMonth6;
    }

    public ArrayList<CourseTableItem> getCourses() {
        return courses;
    }

    public CourseTeacherDetail getCourseTeacher() {
        return courseTeacher;
    }

    public String getSelectedTabIdx() {
        return selectedTabIdx;
    }

    public void setSelectedTabIdx(String selectedTabIdx) {
        this.selectedTabIdx = selectedTabIdx;
    }

    public int getSelectedCoursePupilID() {
        return selectedCoursePupilID;
    }

    public void setSelectedCoursePupilID(int selectedCoursePupilID) {
        this.selectedCoursePupilID = selectedCoursePupilID;
    }

    public int getSelectedTeacherAttendentID() {
        return selectedTeacherAttendentID;
    }

    public void setSelectedTeacherAttendentID(int selectedTeacherAttendentID) {
        this.selectedTeacherAttendentID = selectedTeacherAttendentID;
    }

    public int getSelectedCreditMemoID() {
        return selectedCreditMemoID;
    }

    public void setSelectedCreditMemoID(int selectedCreditMemoID) {
        this.selectedCreditMemoID = selectedCreditMemoID;
    }

    private int getMonthInx(int month, int number) {
        int total = month + number;
        if (total <= 12) {
            return total;
        } else {
            return total - 12;
        }
    }

    public String getCriterial() {
        return criterial;
    }

    public void setCriterial(String criterial) {
        this.criterial = criterial;
    }

    public int getSelectedNewCourseID() {
        return selectedNewCourseID;
    }

    public void setSelectedNewCourseID(int selectedNewCourseID) {
        this.selectedNewCourseID = selectedNewCourseID;
    }

    public String getCriterialCourseName() {
        return criterialCourseName;
    }

    public void setCriterialCourseName(String criterialCourseName) {
        this.criterialCourseName = criterialCourseName;
    }

    public int getCriterialCourseType() {
        return criterialCourseType;
    }

    public void setCriterialCourseType(int criterialCourseType) {
        this.criterialCourseType = criterialCourseType;
    }

    public int getCriterialCourseLevel() {
        return criterialCourseLevel;
    }

    public void setCriterialCourseLevel(int criterialCourseLevel) {
        this.criterialCourseLevel = criterialCourseLevel;
    }

    public String getCriterialStartedDate() {
        return criterialStartedDate;
    }

    public void setCriterialStartedDate(String criterialStartedDate) {
        this.criterialStartedDate = criterialStartedDate;
    }

    public String getCriterialStatus() {
        return criterialStatus;
    }

    public void setCriterialStatus(String criterialStatus) {
        this.criterialStatus = criterialStatus;
    }

    public int getCriterialCourseID() {
        return criterialCourseID;
    }

    public void setCriterialCourseID(int criterialCourseID) {
        this.criterialCourseID = criterialCourseID;
    }

   

}
